#include "pch.h"
#include "SparseMatrix.h"

void CreateMatrix(SMatrix *m) {
	FILE *fp = fopen("Matrix.txt", "r");
	if (fp == NULL)
		exit(1);

	fscanf(fp, "%d %d", &m->mu, &m->nu);

	int value,k=0;
	for (size_t i = 0; i < m->mu; i++)
	{
		for (size_t j = 0; j < m->nu; j++)
		{
			fscanf(fp, "%d", &value);
			if (value != 0) {
				m->data[k].e = value;
				m->data[k].i = i;
				m->data[k].j = j;
				k++;
			}
		}
	}
	m->tu = k;

	fclose(fp);
}

void CopyMatrix(const SMatrix *m, SMatrix *t)
{
	t->mu = m->mu;
	t->nu = m->nu;
	t->tu = m->tu;
	for (size_t i = 0; i < m->tu; i++)
	{
		t->data[i].i = m->data[i].i;
		t->data[i].j = m->data[i].j;
		t->data[i].e = m->data[i].e;
	}
}

void AddMatrix(const SMatrix *m, const SMatrix *n, SMatrix *t)
{

}

void SubMatrix(const SMatrix *m, const SMatrix *n, SMatrix *t)
{

}

void TransposeMatrix(const SMatrix *m, SMatrix *t)
{
	t->mu = m->nu;
	t->nu = m->mu;
	t->tu = m->tu;
	int k = 0;
	if (t->tu != 0)
	{
		for (size_t col = 0; col < m->nu; col++)
		{
			for (size_t i = 0; i < m->tu; i++)
			{
				if (m->data[i].j == col)
				{
					t->data[k].i = m->data[i].j;
					t->data[k].j = m->data[i].i;
					t->data[k].e = m->data[i].e;
					k++;
				}
			}
		}
	}
}

void FastTransposeMatrix(const SMatrix *m, SMatrix *t) {
	t->mu = m->nu;
	t->nu = m->mu;
	t->tu = m->tu;

	int *num = (int*)calloc(t->nu,sizeof(int));
	assert(num != NULL);
	int *cpot= (int*)calloc(t->tu,sizeof(int));
	assert(cpot != NULL);

	if (t->tu != 0)
	{
		for (size_t i = 0; i < m->tu; i++)
		{
			num[m->data[i].j]++;
		}

		for (size_t col = 1; col < m->nu; col++)
		{
			cpot[col] = cpot[col - 1] + num[col - 1];
		}
		
		for (size_t i = 0; i < m->tu; i++)
		{
			size_t col = m->data[i].j, pot = cpot[col];
			t->data[pot].i = m->data[i].j;
			t->data[pot].j = m->data[i].i;
			t->data[pot].e = m->data[i].e;
			cpot[col]++;
		}
	}

	free(num);
	free(cpot);
}